package com.jboost.modules.app.service.strategry.dp;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import com.jboost.common.util.EncryptSha256Util;
import com.jboost.common.util.HttpRestUtils;
import com.jboost.common.util.JSONUtil;
import com.jboost.modules.app.constant.BaseResult;
import com.jboost.modules.app.constant.CustomerDetailInfo;
import com.jboost.modules.app.dto.JdyReq;
import com.jboost.modules.app.dto.XiHuiPeopleDto;
import com.jboost.modules.app.dto.XinHuiCustomerDto;
import com.jboost.modules.app.service.strategry.common.AbstractJdy;
import com.jboost.modules.app.service.strategry.dp.dto.*;
import com.jboost.modules.system.entity.AJdySyncData;
import com.jboost.modules.system.entity.DpGengJing;
import com.jboost.modules.system.mapper.DpGjMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.compress.utils.Lists;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpHeaders;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service(value = "DpGengJingQuery")
@Slf4j
public class DpGengJingQuery extends AbstractJdy<String, DpGengJing, DpGjMapper, DpGengJing>   {


    public String getFormId() {
        return "63f1002839a1fa0008611c03";
    }

    private static String client_id = "4bd568d8dc53feeee63f51085dd00d8ca444ee7525a26af06ba3551f3ffca44cee43a1898d91c1ae";
    private static String client_secret = "11e193f14f848856ab2fec0be5a2b155454e142e96a49402bc162c3e8516ee477975da5991129cb3";

    public HttpHeaders getJdyHeaders(){
        HttpHeaders jdyHeaders = new HttpHeaders();
        jdyHeaders.set("Authorization","Bearer "+ "bdfDElitwqhraWZoCv3uxdv9PysCV605");
        return jdyHeaders;
    }

    public String getAppId() {
        return "64880dc1f3ecc50008fbae61";
    }

    HashMap<String,String> cache = new HashMap<>();


    protected static String getHeader(String scope) throws IOException {
        HashMap<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("grant_type","password");
        paramMap.put("client_id",client_id);
        paramMap.put("client_secret",client_secret);
        paramMap.put("scope",scope);
        paramMap.put("username","icy@dong-pin.com");
        paramMap.put("password", EncryptSha256Util.getSha256Str("DongpinW2025"));
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization","Basic "+ Base64.getEncoder().encodeToString((client_id+":"+client_secret).getBytes()));
        String response = HttpRestUtils.post(tokenUrl, paramMap, headers);
        HashMap hashMap = JSONUtil.fromJson(response, HashMap.class);
        return (String) hashMap.get("access_token");
    };
    @Scheduled(cron = "0 0/55 * * * ?")
    public BaseResult<Boolean> invokeStrategy() throws Exception {
        log.info("开始批量查询客户数据");
        String header = getHeader("company");
        List<String> ids = Lists.newArrayList();
        cache.clear();
        queryAndPush(header, 1, ids);
        List<DpGengJing> sysUserDeparts = baseMapper.selectList(Wrappers.lambdaQuery(DpGengJing.class).notIn(DpGengJing::getId, ids));
        for (DpGengJing sysUserDepart : sysUserDeparts) {
            jdyDelete(sysUserDepart.getJdyId());

        }
        return BaseResult.success();
    }

    public void queryAndPush(String header, Integer index, List<String> ids) throws Exception {
        HashMap<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("start_index", index);
        paramMap.put("count", 1000);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + header);

//        String s = HttpRestUtils.get("https://api-sandbox.xiaoman.cn/v1/company/fields", Maps.newHashMap(), headers);
//        System.out.println(s);
        //String custmorResponse = HttpRestUtils.get(customersUrl, paramMap, headers);
        OkHttpClient cclient = new OkHttpClient();
        Request request1 = new Request.Builder()
                .url(gjdtUrl + getParams(paramMap)).addHeader("Authorization", "Bearer " + header).get()
                .build();
        Response execute1 = cclient.newCall(request1).execute();
        String custmorResponse = execute1.body().string();
        DongPingGenJingInfo customerInfo = JSONUtil.fromJson(custmorResponse, DongPingGenJingInfo.class);
        customerInfo.getData().getList().forEach(e -> {
             try{
                 DpGengJing dpGengJing = baseMapper.selectById(e.getFollow_up_id());
                 if (Objects.isNull(dpGengJing)) {
                    addGJ(e,header);
                } 
            } catch (Exception ex) {
                log.error("查询客户{}数据失败", ex);
            }
        });
        if (CollectionUtil.isNotEmpty(customerInfo.getData().getList())) {
            queryAndPush(header, 1 + index, ids);
        }
    }

    private void addGJ(FollowUpRecord dpGengJing,String header) throws IOException {
        Map map = new HashMap();
        map.put("company_id", dpGengJing.getCompany_id());
        map.put("format", 0);
        HttpHeaders newHeaders = new HttpHeaders();
        newHeaders.set("Authorization", "Bearer " + header);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(customerDetailUrl + getParams(map)).addHeader("Authorization", "Bearer " + header).get()
                .build();
        Response execute = client.newCall(request).execute();
        // String custmoerDetailResponse = HttpRestUtils.get(customerDetailUrl+getParams(map), map, newHeaders);
        // log.info("custmoerDetailResponse"+custmoerDetailResponse);
        String body = execute.body().string();
        CustomerDetailInfo customerDetailInfo = JSONUtil.fromJson(body, CustomerDetailInfo.class);
        CustomerDetailInfo.DataBean data = customerDetailInfo.getData();
        List<CustomerDetailInfo.DataBean.CompanyBean> company = data.getCompany();
        List<CustomerDetailInfo.DataBean.CompanyBean.FieldsBean> fieldsBeans = company.stream().flatMap(entry -> entry.getFields().stream()).collect(Collectors.toList());
        //fieldsBeans.addAll(customerDetailInfo.getData().getExternal_field_data());
        Map<String, String> fieldMap = fieldsBeans.stream().collect(Collectors.toMap(CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getId, CustomerDetailInfo.DataBean.CompanyBean.FieldsBean::getValue, (a, b) -> a));



        HashMap<String, Object> param = getParam();
        //todo
        FollowUpWidgetReq followUpWidgetReq = new FollowUpWidgetReq();
        followUpWidgetReq.setKhid(getParaMap(dpGengJing.getCompany_info().getCompany_id()));
        followUpWidgetReq.setKhmc(getParaMap(fieldMap.get("name")));
        followUpWidgetReq.setKhjc(getParaMap(fieldMap.get("short_name")));
        followUpWidgetReq.setGjfs(getParaMap(FollowUpType.fromCode(dpGengJing.getType())));
        followUpWidgetReq.setLrfs(getParaMap("小满自动同步"));
        followUpWidgetReq.setJjcd(getParaMap("一般"));
        followUpWidgetReq.setGjnr(getParaMap(dpGengJing.getContent()));
        if (Objects.nonNull(dpGengJing.getCreate_user_info())) {
            if (cache.keySet().contains(dpGengJing.getCreate_user_info().getNickname())){
                followUpWidgetReq.setGjr(getParaMap(cache.get(dpGengJing.getCreate_user_info().getNickname())));
                return;
            }
            JdyReq jdyReq = new JdyReq();
            jdyReq.setApp_id(getAppId());
            jdyReq.setEntry_id("68d10826b10273b43196e208");
            jdyReq.setLimit(100);
            jdyReq.setFields(Arrays.asList("_widget_1758529574651", "_widget_1758529574650"));
            JdyReq.FilterBean filterBean = new JdyReq.FilterBean();
            filterBean.setRel("and");
            List<JdyReq.FilterBean.CondBean> cond = new ArrayList<>();
            JdyReq.FilterBean.CondBean a = new JdyReq.FilterBean.CondBean();
            a.setField("_widget_1758529574651");
            a.setType("text");
            a.setMethod("eq");
            a.setValue(Arrays.asList(dpGengJing.getCreate_user_info().getNickname()));
            cond.add(a);
            filterBean.setCond(cond);
            jdyReq.setFilter(filterBean);

            String s = jdyQueryAll(jdyReq);
            JSONArray jsonArray = (JSONArray) JSONUtil.fromJson(s, HashMap.class).get("data");
            if (jsonArray.size() > 0) {
                DongPingPeopleDto dataBean = JSONUtil.fromJson(JSONUtil.toJson(jsonArray.get(0)), DongPingPeopleDto.class);
                followUpWidgetReq.setGjr(getParaMap(dataBean.get_widget_1758529574650().getUsername()));
                cache.put(dpGengJing.getCreate_user_info().getNickname(),dataBean.get_widget_1758529574650().getUsername());
            }
            cache.put(data.getOwner().get(0).getNickname(),null);
        }
        followUpWidgetReq.setGjdq(getParaMap(customerDetailInfo.getData().getCountry_name()));
        param.put("data", followUpWidgetReq);
        String post = HttpRestUtils.post(add_api, param, getJdyHeaders());
        HashMap hashMap = JSONUtil.fromJson(post, HashMap.class);
        log.info("表单新增结果{}", post);
        DpGengJing userDepart = new DpGengJing();
        userDepart.setId(dpGengJing.getFollow_up_id());
        userDepart.setJdyId(((JSONObject) hashMap.get("data")).getString("_id"));
        userDepart.setData(JSONUtil.toJson(dpGengJing));
        baseMapper.insert(userDepart);
    }
}
